package cn.iocoder.yudao.module.system.service.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.infra.service.config.ConfigService;
import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO;
import cn.iocoder.yudao.module.system.controller.app.config.vo.AppSystemInfoRespVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 移动端系统配置 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class AppSystemConfigServiceImpl implements AppSystemConfigService {

    @Resource
    private ConfigService configService;

    @Value("${yudao.demo:false}")
    private Boolean demoMode;

    /**
     * 需要获取的配置键名列表
     */
    private static final List<String> CONFIG_KEYS = Arrays.asList(
            "sysInfo", "fileUpload", "chatInfo", "compass"
    );

    @Override
    public AppSystemInfoRespVO getSystemInfo() {
        try {
            // 先获取默认配置作为基础
            AppSystemInfoRespVO systemInfo = getDefaultSystemInfo();
            
            // 用数据库中的配置覆盖默认配置
            for (String configKey : CONFIG_KEYS) {
                ConfigDO config = configService.getConfigByKey(configKey);
                if (config != null && StrUtil.isNotBlank(config.getValue())) {
                    Map<String, Object> configValue = parseConfigValue(config.getValue());
                    
                    switch (configKey) {
                        case "sysInfo":
                            systemInfo.setSysInfo(configValue);
                            break;
                        case "fileUpload":
                            systemInfo.setFileUpload(parseFileUploadConfig(configValue));
                            break;
                        case "chatInfo":
                            systemInfo.setChatInfo(configValue);
                            break;
                        case "compass":
                            systemInfo.setCompass(configValue);
                            break;
                    }
                } else {
                    log.info("配置项 [{}] 不存在或为空，使用默认配置", configKey);
                }
            }

            return systemInfo;
        } catch (Exception e) {
            log.error("获取系统配置信息失败", e);
            // 返回默认配置
            return getDefaultSystemInfo();
        }
    }

    /**
     * 解析配置值
     */
    private Map<String, Object> parseConfigValue(String value) {
        try {
            if (JSONUtil.isTypeJSON(value)) {
                return JSONUtil.toBean(value, Map.class);
            } else {
                // 如果不是JSON格式，返回包含原始值的Map
                Map<String, Object> result = new HashMap<>();
                result.put("value", value);
                return result;
            }
        } catch (Exception e) {
            log.warn("解析配置值失败: {}", value, e);
            Map<String, Object> result = new HashMap<>();
            result.put("value", value);
            return result;
        }
    }

    /**
     * 解析文件上传配置，只返回指定字段
     */
    private AppSystemInfoRespVO.FileUploadConfig parseFileUploadConfig(Map<String, Object> configValue) {
        AppSystemInfoRespVO.FileUploadConfig fileUpload = new AppSystemInfoRespVO.FileUploadConfig();
        if (configValue != null) {
            fileUpload.setSize(convertToString(configValue.get("size")));
            fileUpload.setPreview(convertToString(configValue.get("preview")));
            // fileExt 保持原格式：数组就是数组，字符串就是字符串
            fileUpload.setFileExt(configValue.get("fileExt"));
        }
        return fileUpload;
    }

    /**
     * 安全地将对象转换为字符串
     */
    private String convertToString(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof String) {
            return (String) value;
        }
        // 如果是数组或其他类型，转换为JSON字符串
        return JSONUtil.toJsonStr(value);
    }

    /**
     * 获取默认系统配置（多租户支持）
     */
    private AppSystemInfoRespVO getDefaultSystemInfo() {
        AppSystemInfoRespVO systemInfo = new AppSystemInfoRespVO();
        
        // 默认系统信息配置
        Map<String, Object> defaultSysInfo = new HashMap<>();
        defaultSysInfo.put("logo", "");
        defaultSysInfo.put("name", "look-im");
        defaultSysInfo.put("state", "1");
        defaultSysInfo.put("diyName", "0");
        defaultSysInfo.put("regauth", "0");
        defaultSysInfo.put("regtype", "2");
        defaultSysInfo.put("runMode", "1");
        defaultSysInfo.put("ipregion", "1");
        defaultSysInfo.put("closeTips", "系统升级维护中，请稍候再试！");
        defaultSysInfo.put("description", "一款基于vue2.0的即时通信系统");
        defaultSysInfo.put("multipleLogin", "0");
        defaultSysInfo.put("registerInterval", "600");
        systemInfo.setSysInfo(defaultSysInfo);
        
        // 默认聊天配置
        Map<String, Object> defaultChatInfo = new HashMap<>();
        defaultChatInfo.put("stun", "");
        defaultChatInfo.put("online", "1");
        defaultChatInfo.put("webrtc", "1");
        defaultChatInfo.put("dbDelMsg", "1");
        defaultChatInfo.put("msgClear", "1");
        defaultChatInfo.put("redoTime", "120");
        defaultChatInfo.put("stunPass", "");
        defaultChatInfo.put("stunUser", "");
        defaultChatInfo.put("groupChat", "1");
        defaultChatInfo.put("simpleChat", "1");
        
        // 默认自动添加用户配置
        Map<String, Object> autoAddUser = new HashMap<>();
        autoAddUser.put("status", "0");
        autoAddUser.put("welcome", "你好啊，欢迎来到look-im");
        autoAddUser.put("user_ids", Arrays.asList("1", "2", "3"));
        autoAddUser.put("user_items", Arrays.asList("1", "2", "3"));
        defaultChatInfo.put("autoAddUser", autoAddUser);
        
        defaultChatInfo.put("msgClearDay", "30");
        
        // 默认自动添加群组配置
        Map<String, Object> autoAddGroup = new HashMap<>();
        autoAddGroup.put("name", "春游交流");
        autoAddGroup.put("status", "0");
        autoAddGroup.put("userMax", "100");
        autoAddGroup.put("owner_uid", "1");
        
        Map<String, Object> ownerInfo = new HashMap<>();
        ownerInfo.put("id", "1");
        ownerInfo.put("avatar", "");
        ownerInfo.put("user_id", "1");
        ownerInfo.put("realname", "管理员");
        autoAddGroup.put("owner_info", Arrays.asList(ownerInfo));
        defaultChatInfo.put("autoAddGroup", autoAddGroup);
        
        defaultChatInfo.put("groupUserMax", "0");
        defaultChatInfo.put("sendInterval", "0");
        systemInfo.setChatInfo(defaultChatInfo);
        
        // 默认文件上传配置
        AppSystemInfoRespVO.FileUploadConfig defaultFileUpload = new AppSystemInfoRespVO.FileUploadConfig();
        defaultFileUpload.setSize("50");
        defaultFileUpload.setPreview("");
        defaultFileUpload.setFileExt(Arrays.asList(
            "jpg", "jpeg", "ico", "webp", "bmp", "gif", "pdf", "mp3", "wav", "wmv", 
            "amr", "mp4", "3gp", "avi", "m2v", "mkv", "mov", "ppt", "pptx", "doc", 
            "docx", "xls", "xlsx", "txt", "md", "hevc", "png"
        ));
        systemInfo.setFileUpload(defaultFileUpload);
        
        // 默认罗盘配置
        Map<String, Object> defaultCompass = new HashMap<>();
        defaultCompass.put("list", Arrays.asList());
        defaultCompass.put("mode", 1);
        defaultCompass.put("status", 0);
        systemInfo.setCompass(defaultCompass);
        
        // 设置演示模式
        systemInfo.setDemonMode(demoMode);
        
        return systemInfo;
    }
}